package com.spring.demo.hystrix;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class HystrixDemoApplication {
    public static void main(String[] args) {
        HelloWorld realObject = new HelloWorldImpl();
        HelloWorld proxyInstance = (HelloWorld) Proxy.newProxyInstance(
                HelloWorldImpl.class.getClassLoader(),
                new Class[]{HelloWorld.class},
                new AdvancedInvocationHandler(realObject));
 
        // 模拟多次调用以观察限流和熔断效果
        for (int i = 0; i < 10; i++) {
            proxyInstance.sayHello();
        }
    }
    static class AdvancedInvocationHandler implements InvocationHandler {
        private final Object target;
        private AtomicInteger requestCount = new AtomicInteger(0);
        private AtomicLong lastTimestamp = new AtomicLong(System.currentTimeMillis());
        private volatile boolean circuitBreakerOpen = false;
        private final long cooldownPeriod = 10000; // 冷却时间10秒
 
        public AdvancedInvocationHandler(Object target) {
            this.target = target;
        }
 
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            long now = System.currentTimeMillis();
 
            // 检查熔断器是否应该被重置
            if (circuitBreakerOpen && (now - lastTimestamp.get() > cooldownPeriod)) {
                circuitBreakerOpen = false; // 重置熔断器
                requestCount.set(0); // 重置请求计数
                System.out.println("Circuit breaker has been reset.");
            }
 
            // 熔断检查
            if (circuitBreakerOpen) {
                System.out.println("Circuit breaker is open. Blocking method execution for: " + method.getName());
                return null; // 在实际场景中，可以返回一个兜底的响应或抛出异常
            }
 
            // 限流检查
            if (requestCount.incrementAndGet() > 5) {
                if (now - lastTimestamp.get() < cooldownPeriod) { // 10秒内超过5次请求，触发熔断
                    circuitBreakerOpen = true;
                    lastTimestamp.set(now); // 更新时间戳
                    System.out.println("Too many requests. Opening circuit breaker.");
                    return null; // 触发熔断时的处理
                } else {
                    // 重置计数器和时间戳
                    requestCount.set(0);
                    lastTimestamp.set(now);
                }
            }
 
            // 执行实际方法
            Object result = method.invoke(target, args);
 
            // 方法执行后的逻辑
            System.out.println("Executed method: " + method.getName());
 
            return result;
        }
    }
}
